<template>
  <div
    id="userLayout"
    class="w-full h-full relative"
  >
    <div
      class="rounded-lg flex items-center justify-evenly w-full h-full bg-white md:w-screen md:h-screen md:bg-[#194bfb]"
    >
      <div class="md:w-3/5 w-10/12 h-full flex items-center justify-evenly" style="background: #ffffff">
        <div class="oblique h-[130%] w-3/5 bg-white transform -rotate-12 absolute -ml-52" />
        <!-- 分割斜块 -->
        <div class="z-[999] pt-12 pb-10 md:w-96 w-full  rounded-lg flex flex-col justify-between box-border">
          <div>
            <div class="flex items-center justify-center">
              <img
                class="w-24"
                :src="$GIN_VUE_ADMIN.appLogo"
                alt
              >
<!--              src="../../image/微信图片_20231205190514.jpg"-->

            </div>
            <div class="mb-9">
              <p class="text-center text-4xl font-bold">综合面试题管理平台</p>
              <p class="text-center text-sm font-normal text-gray-500 mt-2.5">创始人:2103A唐建林
              </p>
            </div>
            <el-form
              ref="loginForm"
              :model="loginFormData"
              :rules="rules"
              :validate-on-rule-change="false"
              @keyup.enter="submitForm"
            >
              <el-form-item
                prop="userName"
                class="mb-6"
              >
                <el-input
                  v-model="loginFormData.userName"
                  size="large"
                  placeholder="请输入用户名"
                  suffix-icon="user"
                />
              </el-form-item>
              <el-form-item
                prop="password"
                class="mb-6"
              >
                <el-input
                  v-model="loginFormData.password"
                  show-password
                  size="large"
                  type="password"
                  placeholder="请输入密码"
                />
              </el-form-item>
              <el-form-item
                v-if="loginFormData.openCaptcha"
                prop="captcha"
                class="mb-6"
              >
                <div class="flex w-full justify-between">
                  <el-input
                    v-model="loginFormData.captcha"
                    placeholder="请输入验证码"
                    size="large"
                    class="flex-1 mr-5"
                  />
                  <div class="w-1/3 h-11 bg-[#c3d4f2] rounded">
                    <img
                      v-if="picPath"
                      class="w-full h-full"
                      :src="picPath"
                      alt="请输入验证码"
                      @click="loginVerify()"
                    >
                  </div>
                </div>
              </el-form-item>
              <el-form-item class="mb-6">
                <el-button
                  class="shadow shadow-blue-600 h-11 w-full"
                  type="primary"
                  size="large"
                  @click="submitForm"
                >登 录</el-button>
              </el-form-item>
              <el-form-item class="mb-6">
                <el-button
                  class="shadow shadow-blue-600 h-11 w-full"
                  type="primary"
                  size="large"
                  @click="checkInit"
                >前往注册</el-button>

              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="hidden md:block w-1/2 h-full float-right bg-[#194bfb]"><img
        class="h-full"
        src="../../image/20231205192622.png"
        style="width: 100%"
        alt="banner"
      ></div>
<!--      src="@/assets/login_right_banner.jpg"-->
    </div>

    <BottomInfo class="left-0 right-0 absolute bottom-3 mx-auto  w-full z-20">
      <div class="links items-center justify-center gap-2 hidden md:flex">
        <a
          href="http://doc.henrongyi.top/"
          target="_blank"
        >
          <img
            src="@/assets/docs.png"
            class="w-8 h-8"
            alt="文档"
          >
        </a>
        <a
          href="https://support.qq.com/product/371961"
          target="_blank"
        >
          <img
            src="@/assets/kefu.png"
            class="w-8 h-8"
            alt="客服"
          >
        </a>
        <a
          href="https://github.com/flipped-aurora/gin-vue-admin"
          target="_blank"
        >
          <img
            src="@/assets/github.png"
            class="w-8 h-8"
            alt="github"
          >
        </a>
        <a
          href="https://space.bilibili.com/322210472"
          target="_blank"
        >
          <img
            src="@/assets/video.png"
            class="w-8 h-8"
            alt="视频站"
          >
        </a>
      </div>
    </BottomInfo>
    <div>
      <el-dialog
          v-model="addUserDialog"
          title="用户"
          :show-close="false"
          :close-on-press-escape="false"
          :close-on-click-modal="false"
      >
        <div style="height:60vh;overflow:auto;padding:0 12px;">
          <el-form
              ref="userForm"
              :rules="rules"
              :model="userInfo"
              label-width="80px"
          >
            <el-form-item
                v-if="dialogFlag === 'add'"
                label="用户名"
                prop="userName"
            >
              <el-input v-model="userInfo.userName" />
            </el-form-item>
            <el-form-item
                v-if="dialogFlag === 'add'"
                label="密码"
                prop="password"
            >
              <el-input v-model="userInfo.password" />
            </el-form-item>
            <el-form-item
                label="昵称"
                prop="nickName"
            >
              <el-input v-model="userInfo.nickName" />
            </el-form-item>
            <el-form-item
                label="班级号"
                prop="class_id"
            >
<!--              <el-input v-model="userInfo.phone" />-->
              <el-select  v-model="userInfo.ClassID" class="m-2" placeholder="请选择班级" size="small">
                <el-option
                    v-for="item in classs"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
                label="邮箱"
                prop="email"
            >
              <el-input v-model="userInfo.email" />
            </el-form-item>
<!--            <el-form-item-->
<!--                label="用户角色"-->
<!--                prop="authorityId"-->
<!--            >-->
<!--              <el-cascader-->
<!--                  v-model="userInfo.authorityIds"-->
<!--                  style="width:100%"-->
<!--                  :options="authOptions"-->
<!--                  :show-all-levels="false"-->
<!--                  :props="{ multiple:true,checkStrictly: true,label:'authorityName',value:'authorityId',disabled:'disabled',emitPath:false}"-->
<!--                  :clearable="false"-->
<!--              />-->
<!--            </el-form-item>-->
            <el-form-item
                label="启用"
                prop="disabled"
            >
              <el-switch
                  v-model="userInfo.enable"
                  inline-prompt
                  :active-value="1"
                  :inactive-value="2"
              />
            </el-form-item>
            <el-form-item
                label="头像"
                label-width="80px"
            >
              <div
                  style="display:inline-block"
                  @click="openHeaderChange"
              >
                <img
                    v-if="userInfo.headerImg"
                    alt="头像"
                    class="header-img-box"
                    :src="(userInfo.headerImg && userInfo.headerImg.slice(0, 4) !== 'http')?path+userInfo.headerImg:userInfo.headerImg"
                >
                <div
                    v-else
                    class="header-img-box"
                >从媒体库选择</div>
              </div>
            </el-form-item>

          </el-form>

        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="closeAddUserDialog">取 消</el-button>
            <el-button
                type="primary"
                @click="enterAddUserDialog"
            >确 定</el-button>
          </div>
        </template>
      </el-dialog>
      <ChooseImg
          ref="chooseImg"
          :target="userInfo"
          :target-key="`headerImg`"
      />
    </div>
  </div>
</template>

<script setup>
import {
  register, setUserInfo,getClassList
} from '@/api/user'
import { captcha } from '@/api/user'
// import { checkDB } from '@/api/initdb'
import BottomInfo from '@/view/layout/bottomInfo/bottomInfo.vue'
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
// import { useRouter } from 'vue-router'
import { useUserStore } from '@/pinia/modules/user'
import ChooseImg from '@/components/chooseImg/index.vue'
defineOptions({
  name: 'Login',
})

// const router = useRouter()
// 验证函数
const checkUsername = (rule, value, callback) => {
  if (value.length < 5) {
    return callback(new Error('请输入正确的用户名'))
  } else {
    callback()
  }
}
const checkPassword = (rule, value, callback) => {
  if (value.length < 6) {
    return callback(new Error('请输入正确的密码'))
  } else {
    callback()
  }
}
const classs = ref([])
//1111111111
const getClassData = async() => {
  const class_id = await getClassList({page: 1, pageSize: 999999})
  if (class_id.code === 0) {
    console.log(class_id.data)
    for (let i = 0; i < class_id.data.list.length; i++) {
      classs.value.push({
        "label": class_id.data.list[i].className,
        "value": class_id.data.list[i].classId,
      })
    }
    console.log(classs)
  }
}
getClassData()



// 获取验证码
const loginVerify = () => {
  captcha({}).then(async(ele) => {
    rules.captcha.push({
      max: ele.data.captchaLength,
      min: ele.data.captchaLength,
      message: `请输入${ele.data.captchaLength}位验证码`,
      trigger: 'blur',
    })
    picPath.value = ele.data.picPath
    loginFormData.captchaId = ele.data.captchaId
    loginFormData.openCaptcha = ele.data.openCaptcha
  })
}
loginVerify()

// 登录相关操作
const loginForm = ref(null)
const picPath = ref('')
const loginFormData = reactive({
  userName: 'admin',
  password: '123456',
  captcha: '',
  captchaId: '',
  openCaptcha: false,
})
const rules = reactive({
  captcha: [
    {
      message: '验证码格式不正确',
      trigger: 'blur',
    },
  ],
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, message: '最低5位字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入用户密码', trigger: 'blur' },
    { min: 6, message: '最低6位字符', trigger: 'blur' },
    { validator: checkPassword, trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1([38][0-9]|4[014-9]|[59][0-35-9]|6[2567]|7[0-8])\d{8}$/, message: '请输入合法手机号', trigger: 'blur' },
  ],
  email: [
    { pattern: /^([0-9A-Za-z\-_.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g, message: '请输入正确的邮箱', trigger: 'blur' },
  ],
  authorityId: [
    { required: true, message: '请选择用户角色', trigger: 'blur' }
  ]
})

const userStore = useUserStore()
const login = async() => {
  return await userStore.LoginIn(loginFormData)
}
const submitForm = () => {
  loginForm.value.validate(async(v) => {
    if (v) {
      const flag = await login()
      if (!flag) {
        loginVerify()
      }
    } else {
      ElMessage({
        type: 'error',
        message: '请正确填写登录信息',
        showClose: true,
      })
      loginVerify()
      return false
    }
  })
}

// 跳转初始化
// const checkInit = async() => {
//   const res = await checkDB()
//   if (res.code === 0) {
//     if (res.data?.needInit) {
//       userStore.NeedInit()
//       router.push({ name: 'Init' })
//     } else {
//       ElMessage({
//         type: 'info',
//         message: '已配置数据库信息，无法初始化',
//       })
//     }
//   }
// }
const userForm = ref(null)
const enterAddUserDialog = async() => {
  userInfo.value.authorityId = userInfo.value.authorityIds[0]
  userForm.value.validate(async valid => {
    if (valid) {
      const req = {
        ...userInfo.value
      }
      console.log(req)
      if (dialogFlag.value === 'add') {
        const res = await register(req)
        if (res.code === 0) {
          ElMessage({ type: 'success', message: '创建成功' })
          closeAddUserDialog()
        }
      }
      if (dialogFlag.value === 'edit') {
        const res = await setUserInfo(req)
        if (res.code === 0) {
          ElMessage({ type: 'success', message: '编辑成功' })
          await getTableData()
          closeAddUserDialog()
        }
      }
    }
  })
}

const addUserDialog = ref(false)
const closeAddUserDialog = () => {
  userForm.value.resetFields()
  userInfo.value.headerImg = ''
  userInfo.value.authorityIds = []
  addUserDialog.value = false
}

const dialogFlag = ref('add')

const checkInit = () => {
  dialogFlag.value = 'add'
  addUserDialog.value = true
}
// 弹窗相关
const userInfo = ref({
  userName: '',
  password: '',
  nickName: '',
  headerImg: '',
  authorityId: '',
  authorityIds: [],
  enable: 1,
  ClassID:'',
})

const chooseImg = ref(null)
const openHeaderChange = () => {
  chooseImg.value.open()
}
</script>
<style lang="scss">
.header-img-box {
  @apply w-52 h-52 border border-solid border-gray-300 rounded-xl flex justify-center items-center cursor-pointer;
}
</style>
